package ObjectStream;

import JavaIOTest.Person;
import org.junit.Test;

import java.io.*;

/**
 * @author 李泽伟
 */
public class MainTest {
    /**
     * 序列化过程：将内存中的Java对象保存到磁盘二进制文件 .bat文件 中
     */
    @Test
    public void test1() {
        ObjectOutputStream outputStream = null;
        try {
            outputStream = new ObjectOutputStream(new FileOutputStream("object.dat"));
            outputStream.writeObject(new String("江田清"));
            //刷新操作
            outputStream.flush();
            outputStream.writeObject(new Person(14, "李泽江"));
            outputStream.flush();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 反序列化， 使用ObjectInputStream将文件中的Java对象输入到内存中
     */
    @Test
    public void test() {
        ObjectInputStream inputStream = null;
        try {
            inputStream = new ObjectInputStream(new FileInputStream("object.dat"));
            String str = (String) inputStream.readObject();
            System.out.println(str);
            Object o = inputStream.readObject();
            Person p = (Person) o;
            System.out.println(p);
        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
